package com.example.javamaday.tree;

import java.util.Stack;

public class NoRecursionScan {

    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.right.left = new Node(8);
        root.left.right.right = new Node(9);
        postOrder(root);
    }

    public static void preOrder(Node root) {
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node temp = stack.pop();
            if (temp != null) {
                System.out.print(temp.value + " ");
                if (temp.right != null) {
                    stack.push(temp.right);
                }
                if (temp.left != null) {
                    stack.push(temp.left);
                }
            }
        }
    }

    public static void inOrder(Node root) {
        Stack<Node> stack = new Stack<Node>();
        stack.push(root);
        while (root.left != null) {
            stack.push(root.left);
            root = root.left;
        }
        while (!stack.isEmpty()) {
            Node temp = stack.pop();
            if (temp != null) {
                System.out.print(temp.value + " ");
                if (temp.right != null) {
                    Node n1 = temp.right;
                    stack.push(temp.right);
                    while (n1.left != null) {
                        stack.push(n1.left);
                        n1 = n1.left;
                    }
                }
            }
        }
    }

    public static void postOrder(Node root) {
        Stack<Node> stack = new Stack<>();
        Stack<Node> stackPop = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            if (node != null) {
                stackPop.push(node);
                if (node.left != null) {
                    stack.push(node.left);
                }
                if (node.right != null) {
                    stack.push(node.right);
                }
            }
        }
        while (!stackPop.isEmpty()) {
            System.out.print(stackPop.pop().value + " ");
        }
    }

    public static class Node {
        Node left;
        Node right;
        int value;

        public Node(int value) {
            this.value = value;
        }
    }
}
